package com.example.jdcompetition.Service.cvsPro.jd;

import com.example.jdcompetition.Service.cvsPro.time.DeliverTime;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.LinkedList;

import static com.example.jdcompetition.JdcompetitionApplication.deliver;

/**
 * @author henrydai
 * @date 2021/6/19 16:08
 */
@Service
@Slf4j
public class ExeDeliver {

    public long execute(String[] des, long orderDate) {
        String DestinationAddress = des[0]+des[1]+des[2]+des[3];
        int x=4;
        while(x>0)
        {
            LinkedList<DeliverTime> deliverList = deliver.get(DestinationAddress);
            if(deliverList!=null)
            {
                Collections.sort(deliverList);
                DeliverTime dt = getDeliverTime(orderDate,deliverList);
                if(dt!=null)
                {
                    return dt.deliverTime;
                }
            }
            x--;
            if(x<=0)
            {
                log.error("派送失败");
                return -1;
            }
            DestinationAddress="";
            for(int i=0;i<x;i++)
            {
                DestinationAddress+=des[i];
            }
        }
        return -1;
    }

    private DeliverTime getDeliverTime(long orderDate, LinkedList<DeliverTime> deliverList)
    {
        int low=0;
        int high=deliverList.size()-1;
        int mid;
        while(low<high)
        {
            mid=(low+high+1)/2;
            if(deliverList.get(mid).effectiveDate>orderDate)
            {
                high=mid-1;
            }
            else
            {
                low=mid;
            }
        }
        DeliverTime temp = deliverList.get(low);
        //考虑当天揽收时间

        if(temp.effectiveDate>orderDate || orderDate>temp.expirationDate)
            return null;
        else
            return temp;
    }

}
